import connect from "@/utils/mongodb";
import Comment from "@/model/Comment";
import { NextResponse } from "next/server";

// 修改评论状态（PATCH请求）
export const PATCH = async (request, { params }) => {
  try {
    await connect();
    const { id } = await params;
    const { status } = await request.json();

    // 验证状态值合法性
    const validStatuses = ['pending', 'approved', 'rejected'];
    if (!validStatuses.includes(status)) {
      return NextResponse.json({
        message: "无效的状态值，必须是pending/approved/rejected",
        success: false
      }, { status: 400 });
    }

    // 更新评论状态
    const updatedComment = await Comment.findByIdAndUpdate(
      id,
      { status },
      { new: true, runValidators: true } // 返回更新后的文档
    );

    if (!updatedComment) {
      return NextResponse.json({
        message: "评论不存在",
        success: false
      }, { status: 404 });
    }

    return NextResponse.json({
      message: "评论状态更新成功",
      success: true,
      data: updatedComment
    });
  } catch (error) {
    console.error('更新评论状态失败:', error);
    return NextResponse.json({
      message: "更新评论状态失败",
      success: false,
      error: error.message
    }, { status: 500 });
  }
};